package net.kong.yumo.assa.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON; 

import net.hasor.dataway.config.Result;
import redis.clients.jedis.JedisCluster;


/*
 * 拦截验证token 
 * */
public class DatawayInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	@Qualifier("myJedisCluster")
	private JedisCluster jedisCluster;

	private static Logger logger = LoggerFactory.getLogger(DatawayInterceptor.class);
 
	public DatawayInterceptor() {
		
	}
	public DatawayInterceptor(JedisCluster jedisCluster) {
		this.jedisCluster=jedisCluster;
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object handler,
			@Nullable ModelAndView modelAndView) throws Exception {
//		logger.info("httpServletResponse.getCharacterEncoding()");
//		logger.info(httpServletResponse.getCharacterEncoding());
//        httpServletResponse.addHeader("X-Frame-Options", "DENY");
//        httpServletResponse.addHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0");
//        httpServletResponse.addHeader("Cache-Control", "no-cache='set-cookie'");
//        httpServletResponse.addHeader("Pragma", "no-cache");
//        httpServletResponse.addHeader("Content-Type", "application/json;charset=UTF-8");
//		httpServletResponse.setContentType("application/json;charset=UTF-8");
	}
	
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		String uri = request.getRequestURI();
		//心跳检测， 直接放行
		if (uri.equals("/api/heartbeat/v1")) {
			return true;			
		}
	    String msg="";
		String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_CLIENT_IP");  
        } 
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        }  

		logger.info("-------DatawayInterceptor---RemoteAddrip: " + ip);
		logger.info("-------DatawayInterceptor---Print Current Uri: " + uri);
		//请求参数

		String[] value;
		Map<String ,String[]> pars =request.getParameterMap();
		StringBuffer temStr=new StringBuffer();
		for(String par : pars.keySet() ) {
			value=pars.get(par);	
		     for(int i=0;i<value.length;i++){  
		    	 temStr.append(value[i]); 
		    	 temStr.append( "," ); 
		     } 
			logger.info("-----DatawayInterceptor--Print Current ParameterMap: " +
					par + "：" + temStr.toString() );
			temStr.setLength(0);
		}
		//用户验证接口：直接放行
		if (uri.equals("/api/common/beforeUse/v1")) {
			return true;			
		}
		
		
		//非通用接口
		if (uri.startsWith("/api/")) {
			String param = "";
			//请求类型
			String method = request.getMethod();
		
			//GET请求
			if (method.equals("GET")||method.equals("DELETE")) {
				param = request.getParameter("datawayToken");//固定写法："datawayToken"
			}
			//PUT,POST请求
			else if (method.equals("POST")||method.equals("PUT")) {
				param = request.getHeader("datawayToken");//固定写法："datawayToken"
			}

			logger.info("-------DatawayInterceptor---Print Current param: " + param);
			if (param != null && !"".equals(param)) {
				String token = jedisCluster.get(param);
				
				if (token != null) {
					String[] s = token.split("-");
					String keyName = s[0];
					String appKey = s[1];
					logger.info("----------redis SystemAppKey keyName: " + keyName + "------ redis param token: " + param);//打印格式：外部系统名称+外部系统token
					String redisToken = jedisCluster.get(appKey);
					//urlAccessControl(uri,keyName);
					if (redisToken != null && param.equals(redisToken))
						return true;
				}else {
					msg="未通过验证，datawayToken过期";
				}
			}else {
				msg="未通过验证，未能在正确位置发现datawayToken";
			}
			

		}
		
		/**
		 * 页面使用
		 */
		if ( uri.startsWith("/interface-ui/")  || uri.startsWith("/swagger-ui.html")) {
			Cookie[] cookies = request.getCookies();
			//IP地址符合通过
			if( ip.startsWith("10.2.226.")) {
				logger.info("IP地址符合通过");
				return true;
			}
			if (cookies != null && cookies.length > 0) {
				for (Cookie cookie : cookies) {
					if ((cookie.getName().indexOf("datawayToken") > -1)
							&& (jedisCluster.get(cookie.getValue()) != null)) {
						//判断用户所属角色：是否为管理员，管理员放行，非管理员拦截
						//redis value 结构：userId-roleId, 其中roleId结构为roleId1,roleId2,roleId3,......
						String[] userRoleIds = jedisCluster.get(cookie.getValue()).split("-")[1].split(",");
						for (int i = 0; i < userRoleIds.length; i++) {
							logger.info("userRoleId: " + userRoleIds[i] + "      "  + "token: " + cookie.getValue());
							if (isAdmin(userRoleIds[i])) 
								logger.info("cookie符合通过");
								return true;
						}
						msg="没有/api/interface-ui/进入权限-非管理员";
						break;
					}
					msg="没有/api/interface-ui/进入权限-cookie检验失败-网段错误";
				}
			
			}
		}
		if(msg.equals("")) {
			msg="DatawayInterceptor not find path ";
		}
		Result result = result(401,msg);
		response.setContentType("text/json"); //设置成JSON格式的数据，      
		response.setCharacterEncoding("UTF-8"); //防止乱码
		response.getWriter().println(JSON.toJSONString(result).toString());
		logger.info("---------------------未通过验证--------------: "+msg );
		
		return false;
	}
	
	/**
	 * 是否为管理员账号登录-页面登录
	 * @param roleId
	 * @return
	 */
	private boolean isAdmin(String roleId) {
		boolean flag = false;
		if (roleId.equals("402981e85a8284db015a82b3ffc90001") || //综合档案系统超级管理员
				roleId.equals("402881e351b32a560151b32be74f0006") //客户档案系统超级管理员
				|| roleId.equals("8a82628c5876715d0158768778c60141") //综合档案管理员
				) 
			flag =  true;
		return flag;
	}
	private boolean urlAccessControl(String url,String owner) {
		boolean flag = false;

		if( url.startsWith("/api/bpm/")&& owner=="") {
		 
		}
		
		return flag;
	}
	/**
	 * 
	 * @param code
	 * @param msg
	 * @return
	 */
	private Result result(Integer code, String msg) {
		Result<String> result = new Result<String>();
		result.setCode(code);
		result.setMessage(msg);
		result.setResult("");
		result.setSuccess(false);
		return result;
	}

}
